import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:google_fonts/google_fonts.dart';
import '../../function/states/encyclopedia_state.dart';
import '../../function/routes/app_route_manager.dart';
import '../../function/widgets/animated_tap_widget.dart';

/// 百科列表页面
class EncyclopediaListPage extends StatefulWidget {
  final String category;

  const EncyclopediaListPage({super.key, required this.category});

  @override
  State<EncyclopediaListPage> createState() => _EncyclopediaListPageState();
}

class _EncyclopediaListPageState extends State<EncyclopediaListPage> {
  @override
  void initState() {
    super.initState();
    // 监听百科数据变化
    EncyclopediaState.encyclopediaListBeacon.subscribe((encyclopediaList) {
      if (mounted) {
        setState(() {});
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final encyclopediaList =
        widget.category == 'animal'
            ? EncyclopediaState.getAnimalEncyclopedia()
            : EncyclopediaState.getPlantEncyclopedia();

    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/common_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              // 顶部导航栏
              _buildTopNavigationBar(),

              SizedBox(height: 12.w),

              // 百科列表内容
              Expanded(child: _buildEncyclopediaGrid(encyclopediaList)),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopNavigationBar() {
    final title =
        widget.category == 'animal'
            ? 'Animal Encyclopedia'
            : 'Plant Encyclopedia';

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 0.h),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => AppRouteManager.goBack(),
            child: Row(
              children: [
                Icon(Icons.chevron_left, color: Colors.white, size: 26.w),
                SizedBox(width: 12.w),

                // 标题
                Text(title)
                    .fontSize(18.sp)
                    .textColor(Colors.white)
                    .fontFamily(
                      GoogleFonts.quicksand(
                        fontWeight: FontWeight.w700,
                      ).fontFamily,
                    )
                    .fontWeight(FontWeight.w700)
                    .textAlignment(TextAlign.center),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建百科网格列表
  Widget _buildEncyclopediaGrid(List<dynamic> encyclopediaList) {
    return SingleChildScrollView(
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 20.w),
        child: _buildStaggeredGrid(encyclopediaList),
      ),
    );
  }

  /// 构建交错网格布局
  Widget _buildStaggeredGrid(List<dynamic> encyclopediaList) {
    // 将列表分为两列，创建不同高度的卡片
    final leftColumnItems = <Widget>[];
    final rightColumnItems = <Widget>[];

    for (int i = 0; i < encyclopediaList.length; i++) {
      final encyclopedia = encyclopediaList[i];

      if (i % 2 == 0) {
        rightColumnItems.add(_buildEncyclopediaCard(encyclopedia, false));
        rightColumnItems.add(SizedBox(height: 16.h));
      } else {
        leftColumnItems.add(_buildEncyclopediaCard(encyclopedia, true));
        leftColumnItems.add(SizedBox(height: 16.h));
      }
    }

    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 左列 - 占剩余可用宽度的 192/343
        Flexible(flex: 192, child: Column(children: leftColumnItems)),

        SizedBox(width: 12.w),

        // 右列 - 占剩余可用宽度的 141/343
        Flexible(flex: 141, child: Column(children: rightColumnItems)),
      ],
    );
  }

  /// 构建单个百科卡片
  Widget _buildEncyclopediaCard(dynamic encyclopedia, bool isLeftColumn) {
    // 根据列位置设置不同的宽高比
    final screenHeight = MediaQuery.of(context).size.height;

    // 左列卡片：宽高比 192/218
    // 右列卡片：宽高比 141/165
    final cardHeight =
        isLeftColumn
            ? screenHeight *
                (218 / 812) // 左列高度比例
            : screenHeight * (165 / 812); // 右列高度比例

    // 根据宽高比计算卡片宽度
    final cardWidth =
        isLeftColumn
            ? screenHeight *
                (218 / 812) *
                (192 / 218) // 左列：高度 * (192/218)
            : screenHeight * (165 / 812) * (141 / 165); // 右列：高度 * (141/165)

    return AnimatedTapWidget(
      onTap: () {
        // 跳转到百科详情页
        AppRouteManager.navigateToEncyclopediaDetail(
          encyclopedia.encyclopediaId,
        );
      },
      child: Container(
        width: cardWidth,
        height: cardHeight,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12.r),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 8.r,
              offset: Offset(0, 4.h),
            ),
          ],
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(16.r),
          child: Stack(
            children: [
              // 背景图片
              Positioned.fill(
                child: Image.asset(encyclopedia.imageUrl, fit: BoxFit.cover),
              ),

              // 渐变遮罩
              Positioned.fill(
                child: Container(
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [
                        Colors.transparent,
                        Colors.black.withOpacity(0.3),
                        Colors.black.withOpacity(0.7),
                      ],
                      stops: const [0.0, 0.6, 1.0],
                    ),
                  ),
                ),
              ),

              // 标题 - 左上角
              Positioned(
                top: 12.h,
                left: 12.w,
                right: 12.w,
                child: Text(encyclopedia.name)
                    .fontSize(16.sp)
                    .textColor(Colors.white)
                    .fontFamily(
                      GoogleFonts.quicksand(
                        fontWeight: FontWeight.w700,
                      ).fontFamily,
                    )
                    .fontWeight(FontWeight.w700)
                    .textAlignment(TextAlign.left),
              ),

              // View按钮 - 右下角
              Positioned(
                bottom: 12.h,
                right: 12.w,
                child: Container(
                  width: 37.w,
                  height: 37.w,
                  decoration: BoxDecoration(
                    color: const Color(0xFF663507).withOpacity(0.4),
                    borderRadius: BorderRadius.circular(25.r),
                    border: Border.all(
                      color: Colors.white.withAlpha(80),
                      width: 1.w,
                    ),
                  ),
                  child: Center(
                    child: Text('View')
                        .fontSize(11.sp)
                        .textColor(Colors.white)
                        .fontFamily(
                          GoogleFonts.quicksand(
                            fontWeight: FontWeight.w600,
                          ).fontFamily,
                        )
                        .fontWeight(FontWeight.w600),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
